<template>
  <a-card :title="title">
    <div slot="extra">
      <div class="cardRight">
        <a-popconfirm overlayClassName="pop" placement="bottomRight" ok-text="设置" cancel-text="取消" @confirm="columnsSetting">
          <div slot="icon"></div>
          <template slot="title">
            <div class="popconfirm beauty-scroll">
              <a-tree
                v-model="checkedKeys"
                checkable
                :tree-data="treeColumns"
                :replaceFields="{key: columnsKey}"
                draggable
                @drop="onDrop"
              />
            </div>
          </template>
          <a-icon class="setting" type="setting" />
        </a-popconfirm>
        <a-icon @click="download" class="download" type="download" />
      </div>
    </div>
    
    <slot></slot>

    <StandardTable 
      :showAlert="showAlert"
      :columns="iColumns"
      :rowKey="rowKey"
      :dataSource="dataSource"
      :loading="loading"
      :pagination="pagination"
      :scroll="scroll"
      :selectedRows.sync="iSelectedRows"
      @change="onChange"
      @selectedRowChange="selectedRowChange"
    >
      <template slot-scope="{text, record, index}" :slot="slot" v-for="slot in Object.keys($scopedSlots).filter(key => key !== 'expandedRowRender') ">
        <slot :name="slot" v-bind="{text, record, index}"></slot>
      </template>
    </StandardTable>
  </a-card>
</template>

<script>
import StandardTable from './StandardTable.vue'
import { deepCopyArray } from '@/utils/util.js' 
import FileSaver from 'file-saver';
import xlsx from 'xlsx';

export default {
  props: {
    title: String,
    rowKey: [String, Function],
    columns: {
      type: Array,
      default: () => []
    },
    dataSource: Array,
    defaultCeckedKeys: Array,
    loading: Boolean,
    pagination: {
      type: [Object, Boolean],
      default: true
    },
    scroll:{
      type:Object,
      default:()=>{}
    },
    downloadDataSource: Array,
    downloadTitle: {
      type: String,
      default: '数据下载'
    },
    showAlert:{
      type:Boolean,
      default:false
    },
    selectedRows: Array,
  },
  data() {
    return {
      iColumns: [],
      treeColumns: [],
      checkedKeys: [],
      columnsKey: 'dataIndex',
      downloadLoading: false,
      iSelectedRows:[],
    }
  },
  created() {
    this.createColumns()
  },
  mounted() {

  },
  methods: {
    createColumns() {
      this.iColumns = deepCopyArray(this.columns) //深度克隆
      this.treeColumns = deepCopyArray(this.columns)
      this.iSelectedRows = this.selectedRows ? deepCopyArray(this.selectedRows) : undefined
      const defaultSelected = []
      for (let item of this.columns) {
        if (item[this.columnsKey]) {  // 如果有 item[this.columnsKey] item['dataIndex']
          item['_width'] = item['width'] || null
          defaultSelected.push(item[this.columnsKey])
        }
      }
      this.checkedKeys = this.defaultCeckedKeys || defaultSelected
      this.columnsSetting()
    },
    columnsSetting() {
      // 设置Columns
      const iColumns = []
      for (let item of this.treeColumns) { 
        if (item[this.columnsKey] && this.checkedKeys.includes(item[this.columnsKey])) {
          iColumns.push(item)
        }
      }
      this.iColumns = iColumns
    },
    onDrop(info) {
      const dropKey = info.node.eventKey;
      const dragKey = info.dragNode.eventKey;
      const dropPos = info.node.pos.split('-');
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item[this.columnsKey] === key) {
            return callback(item, index, arr);
          }
          if (item.children) {
            return loop(item.children, key, callback);
          }
        });
      };
      const data = [...this.treeColumns];

      // Find dragObject
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      // 只进行一维拖拽
      if ((info.node.children || []).length == 0) {
        let ar;
        let i;
        loop(data, dropKey, (item, index, arr) => {
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
        this.treeColumns = data;
        this.columnsSetting()
      }
    },
    download() {
      // 下载
      let data = []
      this.downloadLoading = true
      const downloadTitle = this.downloadTitle
      if (!this.downloadDataSource) {
        const columns = this.iColumns
        const dataSource = this.dataSource
        const columnsKeys = columns.map(e => e[this.columnsKey])
        const columnsTitles = columns.map(e => e['title'])
        // console.log(dataSource, columnsKeys, columnsTitles)\
        data.push(columnsTitles)
        for (let i of dataSource) {
          const item = []
          for (let j of columnsKeys) {
            let status = Object.prototype.toString.call(i[j])
            if (status === '[object String]' && i[j] != '') {
              let n = Number(i[j])
              if (!Number.isNaN(n)) {
                item.push(n.toFixed(2))
              } else {
                item.push(i[j])
              }
            } else if (status === '[object Number]') {
              item.push(i[j].toFixed(2))
            } else {
              item.push('-')
            }
          }
          data.push(item)
        }
      } else {
        data = this.downloadDataSource
      }
      
      // console.log(data)
      const workbook = xlsx.utils.book_new(); // 创建一个新的工作簿
      const worksheet = xlsx.utils.aoa_to_sheet(data);
      xlsx.utils.book_append_sheet(workbook, worksheet, downloadTitle);
      // 列转换数字格式
      for (let key in worksheet) {
        if(worksheet[key]['t']){
          worksheet[key]['t'] = "n"
        }
      }
      const wbout = xlsx.write(workbook, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'array'
      });
      try {
        FileSaver.saveAs(
        new Blob([wbout], {
          type: 'application/octet-stream;charset=utf-8"'
        }), downloadTitle + '.xlsx');
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout);
      }finally{
        this.downloadLoading = false
      }
      return wbout;
    },
    onChange(pagination, filters, sorter, {currentDataSource}) {
      this.$emit('change', pagination, filters, sorter, {currentDataSource})
    },
    selectedRowChange(selectedRowKeys, selectedRows) {
      this.$emit('selectedRowChange', selectedRowKeys, selectedRows)
    }
  },
  watch: {
    selectedRows(val) {
      this.iSelectedRows = val
    },
    iSelectedRows(val) {
      this.$emit('update:selectedRows', val)
    }
  },
  components: { StandardTable }
}
</script>

<style lang="less" scoped>
.cardRight{
  display: flex;
  align-items: center;
  .setting{
    margin-right: 12px;
    font-size: 18px;
    cursor: pointer;
  }
  .download{
    font-size: 18px;
    cursor: pointer;
  }
}
.pop /deep/.ant-popover-message-title{
  padding-left: 0;
}
</style>
<style lang="less">
.pop{
  .ant-popover-message-title{
    padding-left: 0;
  }
  .ant-tree li span.ant-tree-switcher{
    width: 0;
  }
  .ant-tree li span[draggable], .ant-tree li span[draggable='true']{
    cursor: move;
  }
  .popconfirm{
    max-height: 450px;
    overflow-y: auto;
  }
  .ant-table-placeholder{
    border: none;
  }
}
</style>
